﻿using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GanagroLiteBO;
using GeneralUtilities;


namespace GanagroLite
{
    public partial class FormPesajes : FormOperaciones
    {
        private bool _modoConsulta = false;

        #region Constructor
        public FormPesajes(bool modoConsulta)
        {
            InitializeComponent();
            this.bindingSourceMain.DataSource = new Pesajes();
            currentNota = new NotaBO(TiposOperacion.Pesaje_Carne);
            this.bindingSourceNota.DataSource = currentNota;
            _modoConsulta = modoConsulta;
        }

        #endregion Constructor

        #region Internal methods

        protected internal override object GetIdValue()
        {
            return "FormPesajes - " + _modoConsulta.ToString();
        }

        public override string ToString()
        {
            return "Registro de Pesajes";
        }

        #endregion

        #region BindingSource Events
        private void bindingSourceMain_AddingNew(object sender, AddingNewEventArgs e)
        {
            try
            {
                //currentNota.Fecha = Convert.ToDateTime(this.dtPickerFecha.Text).Date;
                //currentNota.Nota = this.textBoxNota.Text;
                //currentNota.TipoOperacion = TiposOperacion.Pesaje_Carne;

                Pesajes Op = (Pesajes)this.bindingSourceMain.DataSource;
                List<string> nuevoscodigos = (from p in Op select p.CODIGO).ToList<string>();
                e.NewObject = new PESAJES_BO(nuevoscodigos, currentNota,(short)ComboBoxLote.SelectedValue);

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void bindingSourceMain_PositionChanged(object sender, EventArgs e)
        {
            btnGuardar.Enabled = (_modoConsulta == false) && currentNota.Isvalid(true) && (bindingSourceMain.Count > 0);
        }

        #endregion

        #region UI Events

        private void FormPesajes_Load(object sender, EventArgs e)
        {
            this.bindingSourceMain.ResetBindings(true);
            this.ComboBoxLote.ValueMember = "ID";
            this.ComboBoxLote.DisplayMember = "DESCRIPCION";

            // Next line shouldn't take long since Lookup table is cached.
            this.bindingSourceLotes.DataSource = UtilityDB.Loadlotes();
            this.ComboBoxLote.DataSource = bindingSourceLotes;

        }

        private void dtPickerFecha_Validated(object sender, EventArgs e)
        {
           try
            {
                currentNota.Fecha = Convert.ToDateTime(dtPickerFecha.Text).Date;
                currentNota.Cargar();

                // Set warnings (reset to empty if no warnings)
                this.errorProviderNotas.SetError(dtPickerFecha, currentNota.Warnings());

                if (currentNota.Isvalid(true) == false)
                {
                    this.errorProviderNotas.SetError(dtPickerFecha, currentNota.Error);
                }

                btnGuardar.Enabled = (_modoConsulta == false) && currentNota.Isvalid(true) && (bindingSourceMain.Count > 0);

                if (this.bindingSourceMain.Count > 0)
                {
                    ((Pesajes)this.bindingSourceMain.DataSource).Setfecha(Convert.ToDateTime(dtPickerFecha.Text));
                }
            }
            catch (Exception ex)
            {
                  MessageBox.Show(ex.Message);
            }
        }

        private void textBoxNota_TextChanged(object sender, EventArgs e)
        {
            buttonNota.Enabled = !string.IsNullOrEmpty(textBoxNota.Text.Trim());
            btnGuardar.Enabled = (_modoConsulta == false) && currentNota.Isvalid(true) && (bindingSourceMain.Count > 0);
        }

        private void textBoxNota_Validated(object sender, EventArgs e)
        {
            btnGuardar.Enabled = (_modoConsulta == false) && currentNota.Isvalid(true) && (bindingSourceMain.Count > 0);
        }

        private void buttonNota_Click(object sender, EventArgs e)
        {
            base.GuardarNota();
        }

        private void dataGridViewMain_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {

            if ((PESAJES_BO)bindingSourceMain.Current == null)
            {
                return;
            }

            if (e.ColumnIndex == 1)
            {

                switch (((PESAJES_BO)bindingSourceMain.Current).CalidadUltimaGanancia)
                {
                    case TiposGananciaDiaria.Buena:
                        dataGridViewMain[e.ColumnIndex + 1, e.RowIndex].Style.ForeColor = Color.Green;
                        break;
                    case TiposGananciaDiaria.Regular:
                        dataGridViewMain[e.ColumnIndex + 1, e.RowIndex].Style.ForeColor = Color.DarkOrange;
                        break;
                    case TiposGananciaDiaria.Perdida:
                        dataGridViewMain[e.ColumnIndex + 1, e.RowIndex].Style.ForeColor = Color.Red;
                        break;
                    case TiposGananciaDiaria.Erronea:
                        dataGridViewMain[e.ColumnIndex + 1, e.RowIndex].Style.ForeColor = Color.DarkOrchid;
                        break;
                    default:
                        break;
                }

                switch (((PESAJES_BO)bindingSourceMain.Current).CalidadGananciaVida)
                {
                    case TiposGananciaDiaria.Buena:
                        dataGridViewMain[e.ColumnIndex + 2, e.RowIndex].Style.ForeColor = Color.Green;
                        break;
                    case TiposGananciaDiaria.Regular:
                        dataGridViewMain[e.ColumnIndex + 2, e.RowIndex].Style.ForeColor = Color.DarkOrange;
                        break;
                    case TiposGananciaDiaria.Perdida:
                        dataGridViewMain[e.ColumnIndex + 2, e.RowIndex].Style.ForeColor = Color.Red;
                        break;
                    case TiposGananciaDiaria.Erronea:
                        dataGridViewMain[e.ColumnIndex + 2, e.RowIndex].Style.ForeColor = Color.DarkOrchid;
                        break;
                    default:
                        break;
                }

                dataGridViewMain[e.ColumnIndex + 1, e.RowIndex].ToolTipText = ((PESAJES_BO)bindingSourceMain.Current).FechaPesajePrevio.ToShortDateString();
                dataGridViewMain[e.ColumnIndex + 2, e.RowIndex].ToolTipText = ((PESAJES_BO)bindingSourceMain.Current).FechaPrimerPesaje.ToShortDateString();

            }

        }

        private async void buttonStats_Click(object sender, EventArgs e)
        {
            try
            {

            Pesajes pesajes = (Pesajes)this.bindingSourceMain.DataSource;
            if (pesajes.Count > 0 && pesajes.Any(p => p.IsValid(true) == true))
            {
                var t1 =  Task<string>.Run(() => ((pesajes.Where(p => p.IsValid(true) == true).Count().ToString())));
                var t2 =  Task<string>.Run(() => ((int)pesajes.Where(p => p.IsValid(true) == true).Average(p => p.DiasUltPesaje)).ToString());
                var t3 =  Task<string>.Run(() =>((int)pesajes.Where(p => p.IsValid(true) == true).Average(p => p.UltimaGanancia)).ToString() + " grs.");
                var t4 =  Task<string>.Run(() =>((int)pesajes.Where(p => p.IsValid(true) == true).Average(p => p.Diasvida)).ToString());
                var t5 =  Task<string>.Run(() =>((int)pesajes.Where(p => p.IsValid(true) == true).Average(p => p.GananciaVida)).ToString() + " grs.");

                lblregCount.Text = await t1;
                lblDiasUltPesaje.Text =  await t2;
                lblUltGanancia.Text =  await t3;
                lblDiasVida.Text =  await t4;
                lblGananciaVida.Text =  await t5;
            }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dataGridViewMain_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == 0 || e.ColumnIndex == 1)
                {
                    //GANADO_BO bgo = new GANADO_BO(dataGridViewMain[0, e.RowIndex].Value.ToString());
                    MessageBox.Show(GANADO_BO.ListaPesajes(dataGridViewMain[0, e.RowIndex].Value.ToString()), "Lista de pesajes", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dataGridViewMain_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
        {
            try
            {
                GLiteBO gbo = new GLiteBO(dataGridViewMain[0, e.RowIndex].Value.ToString());
                if (gbo.IsValid())
                {
                    this.contextMenuStrip1.AutoSize = true;
                    this.contextMenuStrip1.Items.Clear();
                    this.contextMenuStrip1.Items.Add("Pesajes anteriores:");
                    foreach (string str in gbo.ListaPesajes())
                    {
                        this.contextMenuStrip1.Items.Add(str);
                    }
                }
            }
            catch
            {
            }

        }

        private void btnGuardar_Click(object sender, EventArgs e)
        {
            VGuardar<PESAJES_BO>(this,this.bindingSourceMain,true);
            this.lblDiasUltPesaje.Text = this.lblDiasVida.Text = this.lblGananciaVida.Text = this.lblUltGanancia.Text = this.lblregCount.Text = "0";
        }

        private void btnSalir_Click(object sender, EventArgs e)
        {
            if (confirmaSalir(bindingSourceMain.Count) == false)
            { return; }

            this.bindingSourceMain.CancelEdit();
            this.bindingSourceNota.CancelEdit();
            this.status = string.Empty;
            this.Close();
        }

        private void dataGridViewMain_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Valor en formato Invalido");
        }

        private void dtPickerFecha_Validating(object sender, CancelEventArgs e)
        {
            DateTime dt;

            this.errorProviderNotasFecha.SetError(dtPickerFecha, string.Empty);

            if (DateTime.TryParse(dtPickerFecha.Text, out dt) == false)
            {
                this.errorProviderNotasFecha.SetError(dtPickerFecha, "Formato de fecha invalido");
                e.Cancel = true;
            }

            if (dt > DateTime.Now)
            {
                this.errorProviderNotasFecha.SetError(dtPickerFecha, "La fecha no puede ser en el futuro");
                e.Cancel = true;
            }

        }

        private void dataGridViewMain_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {
                SendKeys.Send("{TAB}{TAB}");
            }
        }

        #endregion

        private async void FormPesajes_Validated(object sender, EventArgs e)
        {
            //Warmup EF so it doesn't take long to validate date

            var tempNota = new NotaBO(TiposOperacion.Pesaje_Carne);
            tempNota.Fecha = System.DateTime.Now;
            await Task.Run(() => tempNota.exists());

        }

    }

    }

